package dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import entity.Article;
import util.DbcpUtil;

public class ArticleDao3 {

	public void add(Article article) {

		QueryRunner run = new QueryRunner(DbcpUtil.getDataSource());

		try {

			// System.out.println("数据库连接成功！");
			String sql = "insert into Article(id, content, posttime, ip) values(?, ?, ?, ?)";

			run.update(sql, article.getId(), article.getContent(),
					new java.sql.Date(article.getPostTime().getTime()), article.getIp());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void update(Article article) {

		QueryRunner run = new QueryRunner(DbcpUtil.getDataSource());

		try {

			// System.out.println("数据库连接成功！");
			String sql = "update article set content=?,postTime=?,ip=? where id=?";

			run.update(sql, article.getContent(), new java.sql.Date(article.getPostTime().getTime()),
					article.getIp(), article.getId());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void delete(String id) {

		QueryRunner run = new QueryRunner(DbcpUtil.getDataSource());

		try {

			// System.out.println("数据库连接成功！");
			String sql = "delete from article where id=?";

			run.update(sql, id);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public Article findById(String id) {
		Article article = null;
		
		QueryRunner run = new QueryRunner(DbcpUtil.getDataSource());

		ResultSetHandler<Article> h = new BeanHandler<Article>(Article.class);
		
		try {
			String sql = "select * from article where id = ?";
			
			article = run.query(sql, h,id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return article;
	}

	public List<Article> findAll() {
		List<Article> articles = new ArrayList<Article>();
		QueryRunner run = new QueryRunner(DbcpUtil.getDataSource());
		ResultSetHandler<List<Article>> h = new BeanListHandler<Article>(Article.class);
		
		try {
			String sql = "select * from article";
			
			articles = run.query(sql, h);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return articles;
	}
	
	public Long count() {
		QueryRunner run = new QueryRunner(DbcpUtil.getDataSource());

		ResultSetHandler<Long>  h = new ScalarHandler<Long>();
		
		try {
			String sql = "select count(*) from article";
			
			return  run.query(sql, h);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
